#include "../source/tcp_server.h"
#include "../source/byte_array.h"
#include "../source/log.h"
#include <bits/types/struct_iovec.h>
#include <cstring>
#include <memory>

class EchoServer:public TcpServer
{
public:
    EchoServer(int type = 1):m_type(type){}

    //客户端连接成功的回调函数  处理新连接的Socket类
    void handleClient(Socket::ptr client) override;

private:    
    int m_type;//输出类型（2:二进制类型  1:文本类型）
};

void EchoServer::handleClient(Socket::ptr client)
{
    log_debug("handleClient:{}", client->toString());
    ByteArray::ptr ba = std::make_shared<ByteArray>();
    while(true)
    {
        ba->clear();
        std::vector<iovec> iovs;
        ba->getWriteBuffers(iovs, 1024);
        
        int rt = client->recv(&iovs[0], iovs.size());
        if(rt == 0)
        {
            log_critical("cient close:{}", client->toString());
            break;
        }
        else if(rt < 0)
        {
            log_error("clent error, rt:{}, errno:{}, errstr:{}", rt, errno, strerror(errno));
            break;
        }
        //getWriteBuffers并没有设置相关成员变量，需要调用setPosition进行设置
        ba->setPosition(ba->getPosition() + rt); 
        ba->setPosition(0);
        if(m_type == 1)
        {
            log_info("{}",ba->toString());
        }
        else 
        {
            log_info("{}", ba->toHexString());
        }
    }
}


int type = 1;
void run()
{
    log_info("server type:{}", type);
    EchoServer::ptr es = std::make_shared<EchoServer>(type);

    auto addr = Address::LookupAny("0.0.0.0:6666");
    while(!es->bind(addr))
    {
        sleep(2);
    }
    es->start();
}


int main(int argc, char** argv)
{
    if(argc < 2)
    {
        log_error("used as [-t] or [-b]");
        return -1;
    }

    if(!strcmp(argv[1], "-b"))
    {
        type = 2;
    }

    IOManager iom(2);
    iom.schedule(run);

    return 0;
}